package com.example.dataservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.dataservice.dto.CompetitionDTO;
import com.example.dataservice.entity.Competition;
import com.example.dataservice.service.impl.CompetitionServiceImpl;
import com.example.dataservice.utils.Result;
import com.example.dataservice.utils.pageParam;
import com.google.gson.Gson;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-01-12
 */
@RestController
@RequestMapping("/api/competition")
public class CompetitionController {
    @Resource
    private CompetitionServiceImpl competitionService;

    private static final String COMPETITION_KEY="competition";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @PostMapping("/list")
    public Result pageSelect(@RequestBody pageParam param){
        Integer page1 = param.getPage();
        Integer limit = param.getLimit();
        int start = (page1 - 1) * limit;

        List<String> list = stringRedisTemplate.opsForList().range(COMPETITION_KEY,0, -1);
        Gson gson = new Gson();
        assert list!=null;
        if(list.isEmpty()){
            LambdaQueryWrapper<Competition> queryWrapper=new LambdaQueryWrapper<>();
            if(param.getT1()!=null&& !param.getT1().isEmpty())queryWrapper.eq(Competition::getCompetitionName,param.getT1());
            if(param.getT2()!=null&& !param.getT2().isEmpty())queryWrapper.eq(Competition::getLocation,param.getT2());
            Page<Competition> pageInfo=new Page<>(param.getPage(), param.getLimit());
            Page<Competition> page = competitionService.page(pageInfo, queryWrapper);
            List<Competition> competitions = competitionService.list();
            List<String> collect = competitions.stream().map(gson::toJson).collect(Collectors.toList());
            Long l = stringRedisTemplate.opsForList().leftPushAll(COMPETITION_KEY, collect);
            System.out.println(l);
            return Result.success(page.getRecords(), page.getTotal());
        }else {
            List<Competition> collect = list.stream().map(i -> gson.fromJson(i, Competition.class)).collect(Collectors.toList());
            List<Competition> res = new ArrayList<>();
            for (int i = start; i < start+limit ; i++) {
                res.add(collect.get(i));
            }
            return Result.success(res,(long)collect.size());
        }


    }

    @PostMapping("/save")
    public Result save(@RequestBody Competition competition){
        if(competition.getId()==null){
            if(competition.getTime().isBefore(LocalDate.now())){
                return Result.fail("保存失败 比赛时间必须不晚于今天");
            }
            competition.setCreateTime(LocalDate.now());
            competitionService.save(competition);
            return Result.success("添加成功");
        }else {
            LambdaUpdateWrapper<Competition> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Competition::getId,competition.getId());
            competitionService.update(competition,updateWrapper);
            rabbitTemplate.convertAndSend("club_queue",competition.getId().toString());
            return Result.success("修改成功");
        }

    }
    @DeleteMapping("/delete/{id}")
    public Result<String > delete(@PathVariable("id")String id){
        competitionService.removeById(id);
        return Result.success("删除成功");
    }
    @PostMapping("/notice")
    public Result<List<CompetitionDTO>> getNotice(){
        LambdaQueryWrapper<Competition> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.gt(Competition::getTime,LocalDate.now());
        queryWrapper.orderByAsc(Competition::getTime);
        Page<Competition> page=new Page<>(1,3);
        List<CompetitionDTO> dtoList = competitionService.page(page, queryWrapper).getRecords()
            .stream().map(item -> {
                CompetitionDTO dto = new CompetitionDTO();
                String s = "队伍" + item.getTeamName1() + "和队伍" + item.getTeamName2() + "将于" + item.getTime() + "在"
                    + item.getLocation() + "进行比赛";
                dto.setCompetitionContent(s);
                dto.setCompetitionTime(item.getTime());
                dto.setCompetitionName(item.getCompetitionName());
                return dto;
            }).collect(Collectors.toList());
        return Result.success(dtoList);
    }
    @PostMapping("/plan")
    public Result<List<CompetitionDTO>> getPlan(){
        LambdaQueryWrapper<Competition> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.ge(Competition::getCreateTime,LocalDate.now());
        queryWrapper.orderByDesc(Competition::getCreateTime);
        Page<Competition> page=new Page<>(1,3);
        List<CompetitionDTO> dtoList = competitionService.page(page, queryWrapper).getRecords()
            .stream().map(item -> {
                CompetitionDTO dto = new CompetitionDTO();
                String s = "队伍" + item.getTeamName1() + "和队伍" + item.getTeamName2() + "将于" + item.getTime() + "在"
                    + item.getLocation() + "进行比赛";
                dto.setCompetitionContent(s);
                dto.setCompetitionTime(item.getCreateTime());
                dto.setCompetitionName(item.getCompetitionName());
                return dto;
            }).collect(Collectors.toList());
        return Result.success(dtoList);
    }
}
